# coding=utf-8
#


import os
import sys
import json
import time
from datetime import datetime

from django.conf import settings

from django.core.management.base import BaseCommand

from iminer.utils import check_pid

from iminer.tidal.models import TidalAgent

from iminer.sm_log import getLogger


logger = getLogger("iminer.tidal.management.commands.daily_delete_tidal_agent")


class Command(BaseCommand):
    help = "定时删除潮汐算力实例"

    def handle(self, *args, **options):
        """ 定时删除潮汐实例算力 """
        task_name = "pid/daily_delete_tidal_agent"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            TidalAgent.objects.filter().delete()
